package com.tg.app.activity.device.list;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.appbase.custom.constant.CommonConstants;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.core.builtin.account.BuiltinAccount;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.log.collection.AppLogManager;
import com.tange.module.socket.SocketIoManager;
import com.tg.app.MultiVersionHelper;
import com.tg.app.R;
import com.tg.app.TGSdk;
import com.tg.app.activity.CloudServiceActivity;
import com.tg.app.activity.account.AboutActivity;
import com.tg.app.activity.account.ToolBoxActivity;
import com.tg.app.helper.TGGlobalConfigHelper;
import com.tg.app.util.UriUtil;
import com.tg.appcommon.android.LanguageUtils;
import com.tg.appcommon.android.TGAlertDialog;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.appcommon.sdk.TGMessageType;
import com.tg.data.helper.DeviceTypeStorage;
import com.tg.login.helper.OverseaLoginManager;
import com.tg.loginex.helper.LoginHelper;

public class MineViewContainer {

    private static final String TAG = "MineViewContainer";

    private Activity activity;
    private boolean isLogout = false;
    private Callback callback;
    private TextView deviceCountTv;

    public MineViewContainer(Activity activity) {
        this.activity = activity;
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    private int layoutId() {

        return R.layout.nav_header_main_button; // "按钮"
    }

    public void setDeviceCount(int count) {
        deviceCountTv.setText(count + activity.getResources().getString(R.string.personal_devices_count));
    }

    public void attach(ViewGroup parent) {

        View rootView = activity.getLayoutInflater().inflate(layoutId(), parent, true);

        TextView textView = rootView.findViewById(R.id.text_phone);
        String account = PreferenceUtil.getString(activity, CommonConstants.PRE_USER_NAME);
        textView.setText(account);

        RelativeLayout relativeLayoutAccount = rootView.findViewById(R.id.rl_nav_header_account);
        RelativeLayout relativeLayoutTool = rootView.findViewById(R.id.rl_nav_header_tool);
        RelativeLayout relativeLayoutHelp = rootView.findViewById(R.id.rl_nav_header_help);
        RelativeLayout relativeLayoutAbout = rootView.findViewById(R.id.rl_nav_header_about);
        RelativeLayout relativeLayoutLogout = rootView.findViewById(R.id.rl_nav_header_logout);
        RelativeLayout relativeLayoutExitSdk = rootView.findViewById(R.id.rl_nav_header_exit_sdk);
        deviceCountTv = rootView.findViewById(R.id.device_count);

        final View.OnClickListener onClickListener = view -> {
            onNavViewClick(view);
        };

        relativeLayoutAccount.setOnClickListener(onClickListener);
        relativeLayoutTool.setOnClickListener(onClickListener);
        relativeLayoutHelp.setOnClickListener(onClickListener);
        relativeLayoutAbout.setOnClickListener(onClickListener);
        relativeLayoutLogout.setOnClickListener(onClickListener);
        if (TGSdk.getInstance().isInitSdk()){
            relativeLayoutExitSdk.setOnClickListener(onClickListener);
        }else{
            relativeLayoutExitSdk.setVisibility(View.GONE);
        }



        final RelativeLayout developerServices = rootView.findViewById(R.id.rl_nav_header_developer);
        if (developerServices != null) {
            developerServices.setVisibility(View.GONE);
            if (!LanguageUtils.isSimChinese(activity)) { // 仅简体中问下，展示入口
                developerServices.setVisibility(View.GONE);
            }
            developerServices.setOnClickListener(view -> {
                String url = TGGlobalConfigHelper.getInstance().getDeveloperServiceUrl();
                if (!TextUtils.isEmpty(url)) {
                    UriUtil.openServePlayImpl(activity, new Intent(), url, view.getContext().getString(R.string.tange_developer_service), 0);
                } else {
                    TGToast.showToast("URL为空");
                }

                if (callback != null) {
                    callback.onClickButton();
                }
            });
        }
    }

    protected void onNavViewClick(View view) {
        int id = view.getId();
        if (id == R.id.rl_nav_header_account) {
//            Intent intent = new Intent(activity, CloudServiceActivity.class);
//            DeviceSettingsInfo info = new DeviceSettingsInfo();
//            info.deviceID = 0;
//            intent.putExtra(DeviceSettingsActivity.EXT_DEVICE_INFO, info);
//            String url = TGGlobalConfigHelper.getInstance().getSettingsAccount();
//            if (StringUtils.isEmpty(url)){
//                url = ApiUrl.UNREGISTRATION_PAGE;
//            }
//            UriUtil.openServePlayImpl(activity, intent, url, ResourcesUtil.getString(R.string.other_account), 0);
            TGToast.showToast("该功能暂未开放");
        } else if (id == R.id.rl_nav_header_tool) {
            Intent toolIntent = new Intent(activity, ToolBoxActivity.class);
            activity.startActivity(toolIntent);
        } else if (id == R.id.rl_nav_header_help) {
            Intent helpIntent = new Intent();
            helpIntent.putExtra(CloudServiceActivity.KEY_WEBURL, "#/pages/help/index");
            helpIntent.putExtra(CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE, 0);
            helpIntent.setClass(activity, CloudServiceActivity.class);
            activity.startActivity(helpIntent);
            AppLogManager.getInstance().uploadSilence("side-menu-feedback");
        } else if (id == R.id.rl_nav_header_about) {
            Intent intent4 = new Intent(activity, AboutActivity.class);
            activity.startActivity(intent4);
        } else if (id == R.id.rl_nav_header_logout) {
            new TGAlertDialog(activity).builder().setTitle(activity.getString(R.string.notice)).setMessage(R.string.confirm_to_logout)
                    .setPositiveButton(activity.getString(R.string.confirm), v -> logout()).setNegativeButton(activity.getString(R.string.cancel), v -> {
            }).show();
        } else if (id == R.id.rl_nav_header_exit_sdk) {
            TGSdk.getInstance().notifyMessage(TGMessageType.MSG_EXIT_TANGE_SDK, "devicelist");
            activity.finish();
        }

        if (callback != null) {
            callback.onClickButton();
        }
    }

    private void logout() {
        if (callback != null) {
            callback.showLoadingView(activity.getString(R.string.logging_out));
        }

        DeviceTypeStorage.clearAllDevice(activity);
        String lastChannel = LoginHelper.getLastLoginChannel();
        TGLog.i(TAG, "logout: lastChannel = " + lastChannel);

        if (CommonConstants.LOGIN_CHANNEL_FACEBOOK.equals(lastChannel)) {
            OverseaLoginManager.logoutFacebook(activity, () -> {
                PreferenceUtil.setString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_USER_NAME, "");
                logoutInternal(true);
            });
        } else if (CommonConstants.LOGIN_CHANNEL_GOOGLE.equals(lastChannel)) {
            OverseaLoginManager.logoutGoogle(activity, () -> {
                PreferenceUtil.setString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_USER_NAME, "");
                logoutInternal(true);
            });
        } else if (CommonConstants.LOGIN_CHANNEL_LINE.equals(lastChannel)) {
            OverseaLoginManager.logoutLine(activity, () -> {
                PreferenceUtil.setString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_USER_NAME, "");
                logoutInternal(true);
            });
        } else {
            logoutInternal(false);
        }
    }

    private void logoutInternal(boolean thirdPartyLogout) {
        TGLog.i(TAG, "logoutInternal: ");
        SocketIoManager.destroyConnection(activity);
        LoginHelper.saveLastLoginChannel("");
        CameraHub.getInstance().removeAll();
        BuiltinAccount.INSTANCE.login().logout(ret -> gotoLauncher(thirdPartyLogout));
    }

    private void gotoLauncher(boolean thirdPartyLogout) {
        if (!isLogout) {
            MultiVersionHelper.gotoLauncher(activity, thirdPartyLogout);
            isLogout = true;
        }
        if (callback != null) {
            callback.hideLoadingView();
        }
    }

    public interface Callback {
        void showLoadingView(String msg);
        void hideLoadingView();
        void onClickButton();
    }
}
